////////////////////////////////////////////////////////////////////////////////
// Filename: light.ps
////////////////////////////////////////////////////////////////////////////////

#include "lightConstBuffer.hlsl"


/////////////
// GLOBALS //
/////////////
Texture2D shaderTexture;
SamplerState SampleType;

//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
    float4 position : SV_POSITION;
	float4 worldPos : POSITION;
	float3 normal : NORMAL;
    float2 tex : TEXCOORD0;
	float color0 : COLOR0;
    float color1 : COLOR1;
};


cbuffer Material : register(b0)
{
	float4  AmbientColor;
	float4  DiffuseColor;
	float4  SpecularColor;
};


////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 psShader(PixelInputType input) : SV_TARGET
{ 
	// Sample the texture pixel at this location.
	float4 textureColor = shaderTexture.Sample(SampleType, input.tex);
	float3 lightDir;
	float lightIntensity;
		
	uint totalLights, dummy;
	GlobalLight.GetDimensions(totalLights, dummy);
	float fLength = 0;
	float4 lightColor = float4(0,0,0,1); 
	for (uint lightIndex = 0; lightIndex < totalLights; ++lightIndex)
	{
		// Invert the light direction for calculations.
		lightDir = GlobalLight[lightIndex].position.xyz - input.worldPos.xyz;
		lightIntensity = saturate(dot(input.normal, normalize(lightDir)));
		fLength = saturate(1 - length(lightDir) / GlobalLight[lightIndex].fRange);
		lightColor += ((GlobalLight[lightIndex].color * lightIntensity) * fLength);
	}

    float4 diffuse = textureColor * saturate(dot(input.normal, LightDirection.xyz)) * DiffuseLight;
    return saturate(diffuse + lightColor * textureColor + AmbientColor * AmbientLight);
}
